# -*- coding: utf-8 -*-
# @file    : app
# @Date    : 2020/11/30
# @Author  :
# @Version : 1.0.0
import os
import threading
import requests
import time

from flask import Flask
from .config import config
from .ws_server import start
from .log import logger as _logger
from .constant import GIT, ROOT_PATH
from ._misc import get_abs_path, proxy, load_file, read_update_info

user_config = config['user']


class App(Flask):
    """
    Flask 启动, 附加 websocket 服务

    """

    def run(self, *args, **kwargs):
        time.sleep(1)
        _logger.info("启动个人市集服务...")
        _logger.info("工作目录: %s" % ROOT_PATH)
        self.check_update()
        th = threading.Thread(target=start, args=(user_config['host'], user_config['live_search_port']))
        th.start()
        return super(App, self).run(host=user_config['host'], use_reloader=False, port=user_config['web_port'])

    @staticmethod
    def check_update():
        """检查更新"""
        try:
            _logger.info("检查远程(git)资源更新...")
            static_dir = get_abs_path(user_config['static_dir'])
            file_path = os.path.join(static_dir, 'UPDATE.txt')
            branch_url = GIT + '/raw/static-latest'
            list_url = branch_url + '/UPDATE.txt'
            _logger.info("拉取资源列表: %s", list_url)
            response = proxy(requests.get, url=list_url, timeout=1)
            if not response or response.status_code != 200:
                _logger.info("获取资源列表失败")
                return
            git_date, git_uuid, git_version = read_update_info(response.text)
            _logger.info("[资源文件信息]远程(git): %s", git_version)
            if os.path.exists(file_path):
                file_content = load_file(file_path).decode('utf-8')
            else:
                file_content = ""
            local_date, local_uuid, local_version = read_update_info(file_content)
            _logger.info("[资源文件信息]本地(loc): %s", local_version)
            if git_date < local_date:
                return
            if git_date == local_date and git_uuid == local_uuid:
                return

            _logger.info("资源文件有可用更新,  可以手动执行更新脚本!!!!!!!")
            _logger.info("资源文件有可用更新,  可以手动执行更新脚本!!!!!!!")
            _logger.info("资源文件有可用更新,  可以手动执行更新脚本!!!!!!!")
        except Exception as e:
            _logger.error(e)
